package com.anli1.service.impl;


import com.anli1.entity.pojo.Coupon;
import com.anli1.entity.pojo.CouponRedemption;
import com.anli1.entity.vo.R;
import com.anli1.mapper.CouponMapper;
import com.anli1.service.ICouponService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-10-05
 */
@Service
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements ICouponService {
@Autowired
    RedisTemplate redisTemplate;
    @Override
    public R publish(Coupon coupon) {
        //判断--太多硬编码了-懒得用常量-谁喜欢改谁改
        coupon= this.ifCoupon(coupon);

        //xxl-job每日扫描-防止错误

       boolean i=save(coupon);
       if(!i)
       {
           return R.error("发布失败");
       }
        redisTemplate.opsForValue().set("coupon"+coupon.getCouponCode().toString(), coupon);
        return R.success(coupon);

    }

    @Override
    public R lsit() {
        //这里偷懒不用游标了
        //权限校验
        Set<String> keys = redisTemplate.keys("coupon*");
        List<Object> values = new ArrayList<>();

        for (String key : keys) {
            values.add(redisTemplate.opsForValue().get(key));
        }

        return R.success(values);
    }

    public Coupon ifCoupon(Coupon coupon)
    {
        if(coupon.getTotalStock()==null)
        {
            coupon.setTotalStock(10);
        }
        if(coupon.getAvailableStock()==null)
        {
            coupon.setAvailableStock(coupon.getTotalStock());
        }
        if(coupon.getStartTime()==null)
        {
            Calendar calendar = Calendar.getInstance();
            coupon.setStartTime(calendar.getTime());
        }
        if(coupon.getEndTime()==null)
        {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_YEAR, 1); // 当前时间加一天
            coupon.setEndTime(calendar.getTime());//默认一天后结束
        }
        if(coupon.getCouponCode()==null)
        {
            coupon.generateCouponCode();
        }
        if(coupon.getStatus()==null)
        {
            coupon.setStatus(0);
        }

        return coupon;
    }
}
